<?php
/**
 * Created by PhpStorm.
 * User: Core
 * Date: 2018/3/12
 * Time: 11:05
 */

namespace App\models;

use App\Libs\ApiMessage;
use Illuminate\Database\Eloquent\Model;
use App\Models\LuckMoney;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class LuckMoneyLog extends Model
{


    private $join = 1;
    private $initiator = 20;

    const CREATE = 0;   //
    const WORKING = 1;  //进行中
    const SUCCESS = 2;  //成功，结束
    const FAIL = 3;     //失败，结束

    protected $table="luckmoney_log"; // 数据库表
    protected $dateFormat = 'U'; // 时间戳

    /**
     * 生成团标识
     */
    public static function create_sign() {
        $str = time() . mt_rand(1000,9999);
        return substr(md5($str),0,20);
    }

    // 获取用户列表
    public static function get_user_list($sign = ''){
        if(!empty($sign)){
            $data = DB::table('luckmoney_log as a')
                ->select('*')
                ->leftJoin('user as b', 'a.open_id', '=', 'b.open_id')
                ->where(function($query)use($sign){
                    $query -> where('a.sign', $sign);
                })->get();
            $data = $data->toArray();
            return $data;
        }
    }

    // 获取唯一标识
    public static function get_sign($id, $open_id){
        $data = DB::table('luckmoney_log as a')
            ->select('a.sign')
            ->leftJoin('team_status as b', 'a.sign', '=', 'b.sign')
            ->where(function($query)use($id,$open_id){
                $query -> where('a.luckmoney_id', $id);
                $query -> where('a.open_id', $open_id);
                $query -> where('a.captain', 1);
                $query -> where('b.val', 1);
            })->first();

        $sign = '';
        if(!empty($data)){
            $sign = $data->sign;
//            print_r($data);exit;
        }
        return $sign;
    }

    // 获取唯一标识
    public static function get_state($sign){
        $state = DB::table('team_status')
            ->select('val as state')
            ->where(function($query)use($sign){
                $query -> where('sign', $sign);
            })->first();
        $state = $state->state;
        return $state;
    }

    public function checkout(Request $request) {
        $openid = $request->openid;
        $message = new ApiMessage();
        //开团的不能参团，不能重复参团
        if ($request->sign) {
            $sign = $request->sign;
            $result = $this->where(['open_id'=>$openid,'sign'=>$sign])->get();
            if ($result) {
                $message->setCode(ApiMessage::FAIL);
                $message->setMessage('不能重复参团');
                return $message;
            }
        }
        //检查参与次数
        if ($request->sign && $request->aid) {
            $aid = $request->aid;
            $result = $this->where(['open_id'=>$openid,'luckmoney_id'=>$aid,'captain'=>0])->get();
            if ($result) {
                $res =  (count($result->toArray()) >= $this->join)? false : true;
                if (!$res) {
                    $message->setCode(ApiMessage::FAIL);
                    $message->setMessage('超过参团次数限制');
                    return $message;
                }
            }
            return true;
        }
        //检查发起次数
        if ($request->aid) {
            $aid = $request->aid;
            $result = $this->where(['open_id'=>$openid,'luckmoney_id'=>$aid,'captain'=>1])->get();
            if ($result) {
                $res =  (count($result->toArray()) >= $this->initiator) ? false : true;
                if (!$res) {
                    $message->setCode(ApiMessage::FAIL);
                    $message->setMessage('超过发团次数限制');
                    return $message;
                }
            }
            return true;
        }

    }

    /**
     * @param $activity_id
     * @return object|bool
     *
     */
    public function get_luck_money_log($activity_id) {
        $luck_money = new LuckMoney();
        $message = new ApiMessage();
        $activity_info = $luck_money->get_luck_money_by_id($activity_id);
        $now = time();
        $start_time = $activity_info['start_time'];
        $end_time = $activity_info['end_time'];
        if ($now < $start_time  || $now > $end_time) {
            $message->setCode(ApiMessage::FAIL);
            $message->setMessage("活动未开始，或者已经超时");
            return $message;
        }
        $res['status'] = 1;
        $res['money'] =  self::create_rand_double($activity_info->money);
        $res['luckmoney_id'] = $activity_info->id;
        $title_array = json_decode($activity_info['title_array'],true);
        $res['title'] = $title_array[mt_rand(0,1)];
        $res['captain'] = 1;
        $res['sign'] = self::create_sign();
        $message->setCode(ApiMessage::SUCCESS);
        $message->setData($res);
        return $message;
    }

    /**
     * @param $sign
     * @return bool|object
     */
    public function get_luck_money_log_by_sign($sign) {
        $message = new ApiMessage();
        //获取团状态
        $team_status_info = DB::table("team_status")->where(['sign'=>$sign])->first();
        //判断团状态是否进行中，否则直接返回状态码
        if ($team_status_info->val == LuckMoneyLog::WORKING) {
            //获取团信息
            $team_info = $this->where(['sign'=>$sign])->orderBy("captain",'desc')
                ->get(['id','luckmoney_id','captain','sign','money']);
            //获取活动信息
            if ($team_info) {
                $now = time();
                //判断是否超过24小时
                if ($team_info[0]['created_at']+(24 * 3600) >= $now) {
                    $message->setCode(ApiMessage::FAIL);
                    $message->setMessage("该团已经超过24小时");
                    return $message;
                }
                $luckMoney = new LuckMoney();
                $activity_info = $luckMoney->get_luck_money_by_id($team_info[0]['luckmoney_id']);

                $start_time = $activity_info['start_time'];
                $end_time = $activity_info['end_time'];
                $total = count($team_info->toArray());
                if ($now < $start_time  || $now > $end_time) {
                    $message->setCode(ApiMessage::FAIL);
                    $message->setMessage("活动未开始，或者已经超时");
                    return $message;
                }
                if ($total >= $activity_info->share_number) {
                    $message->setCode(ApiMessage::FAIL);
                    $message->setMessage("团人数已满");
                    return $message;
                }
                $receive = $balance = 0;
                foreach ($team_info as $obj) {
                    $receive += $obj->money;
                }
                $balance = $activity_info->money - $receive;
                if ($activity_info->share_number - $total == 1) {
                    $res['money'] = sprintf("%0.2f",$balance);
                    $res['status'] = 2;
                } else {
                    $res['money'] = self::create_rand_double(intval($balance));
                    $res['status'] = 1;
                }
                $res['luckmoney_id'] = $activity_info['id'];
                $res['captain'] = 0;
                $res['sign'] =$sign;
                $title_array = json_decode($activity_info['title_array'],true);
                $res['title'] = $title_array[mt_rand(0,1)];
                $message->setCode(ApiMessage::SUCCESS);
                $message->setData($res);
                return $message;
            } else {
                $message->setCode(ApiMessage::FAIL);
                $message->setMessage("未获得该团信息，请检查");
                return $message;
            }
        } else {
            $message->setCode(ApiMessage::FAIL);
            $message->setMessage("该团已结束");
            return $message;
        }
    }


    public function get_team_info($sign,$aid) {
        $luck = new LuckMoney();
        $activity = $luck->find($aid);
        $persons = $this->where(['sign'=>$sign])->orderBy("captain","desc")
            ->get(['open_id','created_at'])->toArray();
        $start_time = $persons[0]['created_at'];
        $persons = Member::listMember(array_column($persons,'open_id'),"openid");
        $result['sign'] = $sign;
        $result['right_number'] = $activity->use_number;  //开团数
        $result['left_number'] = $activity->number - $activity->use_number;  //剩余团数
        $result['need_person'] = $activity->share_number - count($persons);
        $result['share_money'] = $activity->money;
        $result['persons'] = $persons;
        $result['left_time'] = $start_time + (24 * 3600) -time();
        return $result;
    }

    public static function create_rand_double($max) {
        $seed = mt_rand()/mt_getrandmax();
        $figure = mt_rand(0,$max -1);
        return sprintf("%0.2f",$figure + $seed);
    }

    public function add_log($data) {
        $result = false;
        $status = $data['status'];
        unset($data['status']);
        $res3 = true;
        DB::beginTransaction();
        try {
            $this->luckmoney_id = $data['luckmoney_id'];
            $this->open_id = $data['open_id'];
            $this->username = $data['username'];
            $this->head_ico = $data['head_ico'];
            $this->title = $data['title'];
            $this->captain = $data['captain'];
            $this->sign = $data['sign'];
            $this->money = $data['money'];
            $res1 = $this->save();
            if ($status == 2) {
                $res2 = DB::table("team_status")->where(["sign"=>$data['sign']])->update(
                    [
                        "val" => 2
                    ]
                );
            } else {
                $res = DB::table("team_status")->where(["sign"=>$data['sign']])->first();
                $res2 = true;
                if (!$res) {
                    $res2 = DB::table("team_status")->insert([
                        'sign' => $data['sign'],
                        'val' => $status
                    ]);
                    $luck = new LuckMoney();
                    $res3 = $luck->update_used_by_id($this->luckmoney_id);
                }
            }
            if ($res1 && $res2 && $res3) {
                DB::commit();
                $result = true;
            }
        } catch (\Exception $e) {
            DB::rollBack();
        }
        return $result;
    }

}